package com.laisheng.interview.service.impl;


import com.laisheng.interview.mapper.AccountingInfoMapper;
import com.laisheng.interview.mapper.AccountingMapper;
import com.laisheng.interview.mapper.ResumeFileMapper;
import com.laisheng.interview.model.AccountingInfo;
import com.laisheng.interview.model.AccountingInfoWithEvaluation;
import com.laisheng.interview.model.PageResult;
import com.laisheng.interview.model.ResumeFile;
import com.laisheng.interview.service.AccountingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.List;

/**
 * 面试信息服务实现类，处理面试信息的查询、更新等业务逻辑
 */
@Service
public class AccountingServiceImpl implements AccountingService {
    @Autowired
    private AccountingInfoMapper accountingInfoMapper;
    @Autowired
    private AccountingMapper accountingMapper;
    @Autowired
    private ResumeFileMapper resumeFileMapper;

    public List<AccountingInfo> getAllAccountingInfo() {
        return accountingInfoMapper.getAll();
    }

    /**
     * 根据ID查询面试者信息
     * @param id 面试者ID
     * @return 面试者详细信息
     */
    public AccountingInfo getAccountingInfoById(Long id) {
        return accountingInfoMapper.getById(id);
    }
    
    /**
     * 标记面试者通过状态
     * @param id 面试者ID
     * @param isPassed 是否通过
     */
    public void markAsPassed(Long id, Boolean isPassed) {
        accountingInfoMapper.updatePassStatus(id, isPassed);
    }
    
    /**
     * 分页查询面试者信息
     * @param name 姓名模糊查询
     * @param date 日期筛选
     * @param page 页码
     * @param size 每页条数
     * @param sort 排序方式
     * @return 分页查询结果
     */
    @Override
    public PageResult pageQuery(String name, String date, Integer page, Integer size, String sort) {
        // 1. 解析排序参数
        String[] sortParams = sort.split(",");
        String sortField = sortParams[0]; // 排序字段
        String sortDirection = sortParams.length > 1 ? sortParams[1] : "asc"; // 排序方向，默认升序
        String orderBy = sortField + " " + sortDirection;

        // 2. 设置分页和排序
        PageHelper.startPage(page, size, orderBy);

        // 3. 执行查询（包含评价信息）
        List<AccountingInfoWithEvaluation> accountingList = accountingMapper.selectWithEvaluation(name, date);
        
        // 4. 为每个面试信息检查是否有简历文件
        for (AccountingInfoWithEvaluation info : accountingList) {
            ResumeFile resumeFile = resumeFileMapper.getByAccountingInfoId(info.getId());
            info.setHasResume(resumeFile != null);
        }
        
        PageInfo<AccountingInfoWithEvaluation> pageInfo = new PageInfo<>(accountingList);

        // 5. 封装分页结果
        PageResult result = new PageResult();
        result.setData(pageInfo.getList()); // 当前页数据
        result.setTotal(pageInfo.getTotal()); // 总记录数

        return result;
    }
}